package com.example.composewanandroid.ui.screens.home.square

import com.example.composewanandroid.data.repository.HomeRepository
import com.example.composewanandroid.network.manager.ApiManager
import com.example.composewanandroid.network.model.Banner
import com.example.composewanandroid.network.viewmodel.BaseViewModel
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.map
import javax.inject.Inject

class SquareViewModel @Inject constructor(private val repository: HomeRepository) :
    BaseViewModel() {
    private val homeRepository by lazy { HomeRepository() }

    private fun fetchData() {
        val banner = flow {
            kotlinx.coroutines.delay(2000)
            emit(ApiManager.api.getHomeBanner())
        }.map { bean ->
            val result = mutableListOf<Banner>()
            bean.data?.forEach {
                result.add(
                    Banner(
                        title = it.title ?: "",
                        imagePath = it.imagePath ?: "",
                        url = it.url ?: ""
                    )
                )
            }
            result
        }
        val topListFlow = flow {
            emit(ApiManager.api.getHomeList(1, 20))
        }

    }
}
/*
 private fun fetchData() {
        val imageListFlow = flow {
            kotlinx.coroutines.delay(2000)
            emit(service.getBanners())
        }.map { bean ->
            val result = mutableListOf<BannerData>()
            bean.data?.forEach {
                result.add(BannerData(it.title ?: "", it.imagePath ?: "", it.url ?: ""))
            }
            result
        }
        val topListFlow = flow {
            emit(service.getTopArticles())
        }.map {//提升健壮性。
            it.data ?: emptyList()
        }
        viewModelScope.launch {//	适用场景 	需要同步两个独立数据源
            //zip操作符用于将两个 Flow 的最新值组合在一起
            //zip会等待 imageListFlow和 topListFlow都发射了一个值
            //一一对应​​：每次两个 Flow 都发射新值时，都会触发转换函数

            //combine 任一流有新值时组合最新值 需要实时响应任一数据源变化
            imageListFlow.zip(topListFlow) { banners, tops ->
                viewStates =
                    viewStates.copy(imageList = banners, topArticles = tops, isRefreshing = false)
            }.onStart {
                viewStates = viewStates.copy(isRefreshing = true)
            }.catch {
                viewStates = viewStates.copy(isRefreshing = false)
            }.collect()
        }
    }
 */